package com.demon.androidbasic.base

import android.content.Context
import android.content.res.Configuration
import android.os.Build
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import androidx.lifecycle.LifecycleObserver
import com.gyf.immersionbar.ImmersionBar
import com.demon.androidbasic.R
import com.demon.net.handler.DefaultNetErrorHandler
import com.demon.net.handler.INetErrorHandler
import com.demon.androidbasic.titlebar.CommonTitleBar
import com.demon.androidbasic.titlebar.ITitleBar
import com.demon.androidbasic.util.language.MultiLanguageUtil
import com.demon.logger.Logger
import com.demon.net.RpcCallManager
import io.reactivex.Flowable
import io.reactivex.subscribers.ResourceSubscriber

/**
 * Activity 基类
 *
 * Author : zhaozeyang
 * Date : 2020-08-20
 */
open class BaseActivity : AppCompatActivity(), RpcCallManager {
  var mTitleBar: ITitleBar? = null
  private val rpcCallManager: RpcCallManager = RpcCallManager.RpcCallManagerImpl()
  lateinit var mNetErrorHandler: INetErrorHandler

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    // 添加到生命周期管理
    if (rpcCallManager is LifecycleObserver) {
      lifecycle.addObserver(rpcCallManager)
    }
  }

  override fun onPostCreate(savedInstanceState: Bundle?) {
    super.onPostCreate(savedInstanceState)
    createNetErrorHandler()
    initImmersionBar()
    initTitleBar()
  }

  open fun initImmersionBar() {
    ImmersionBar.with(this).fitsSystemWindows(true).statusBarDarkFont(true).statusBarColor(R.color.colorPrimary).init()
  }

  private fun initTitleBar() {
    val toolbar = findViewById<Toolbar>(R.id.title_bar_id)
    toolbar?.apply {
      mTitleBar = CommonTitleBar(this)
      setNavigationView()
//      setSupportActionBar(this)
    }
  }

  fun setNavigationView(
    resId: Int = R.mipmap.icon_back,
    clickEvent: (() -> Unit)? = null
  ) {
    mTitleBar?.getBackBtn()?.setImageResource(resId)
    mTitleBar?.getBackBtn()?.setOnClickListener {
      clickEvent?.invoke() ?: finish()
    }
  }

  inline fun setNavigationView(crossinline clickEvent: () -> Unit) {
    mTitleBar?.getBackBtn()?.setOnClickListener {
      clickEvent.invoke()
    }
  }

  fun setTitleBarTitle(title: String?) {
    mTitleBar?.getTitleView()?.text = title
  }

  fun setTitleBarTitle(title: Int) {
    mTitleBar?.getTitleView()?.setText(title)
  }

  inline fun setRightFirstImgBtn(
    resId: Int,
    crossinline clickEvent: (() -> Unit)
  ) {
    mTitleBar?.getImageRightBtnFirst()?.apply {
      visibility = View.VISIBLE
      setImageResource(resId)
      setOnClickListener {
        clickEvent.invoke()
      }
    }

  }

  open fun createNetErrorHandler() {
    mNetErrorHandler = DefaultNetErrorHandler(this)
  }

  override fun <T> manageRpcCall(
    flowable: Flowable<T>,
    subscribe: ResourceSubscriber<T>
  ) {
    rpcCallManager.manageRpcCall(flowable, subscribe)
  }

  inline fun setRightSecondImgBtn(
    resId: Int,
    crossinline clickEvent: (() -> Unit)
  ) {
    mTitleBar?.getImageRightBtnSecond()?.apply {
      visibility = View.VISIBLE
      setImageResource(resId)
      setOnClickListener {
        clickEvent.invoke()
      }
    }
  }

  open fun setToolbarElevation(elevation: Float) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
      mTitleBar?.setToolbarElevation(elevation)
    }
  }

//  override fun attachBaseContext(newBase: Context?) {
//    super.attachBaseContext(MultiLanguageUtil.attachBaseContext(newBase))
//    //app杀进程启动后会调用Activity attachBaseContext
//    MultiLanguageUtil.getInstance().setConfiguration(newBase)
//  }
//
//  override fun onConfigurationChanged(newConfig: Configuration) {
//    super.onConfigurationChanged(newConfig)
//  }

  override fun attachBaseContext(newBase: Context) {
    val context = MultiLanguageUtil.attachBaseContext(newBase)
    super.attachBaseContext(context)
  }

//  private fun languageWork(context: Context): Context {
//    // 8.0及以上使用createConfigurationContext设置configuration
//    return if (VERSION.SDK_INT >= VERSION_CODES.O) {
//      updateResources(context)
//    } else {
//      context
//    }
//  }
//
//  @RequiresApi(api = VERSION_CODES.O) private fun updateResources(context: Context): Context {
//    val resources = context.resources
//    val locale: Locale = LanguageUtil.getLocale(context) ?: return context
//    val configuration = resources.configuration
//    configuration.setLocale(locale)
//    configuration.setLocales(LocaleList(locale))
//    return context.createConfigurationContext(configuration)
//  }

  override fun onPause() {
    super.onPause()
    Logger.d(TAG, "$this  onPause ~~~~~~~~~~~~~~~~~~")
  }

  override fun onStop() {
    super.onStop()
    Logger.d(TAG, "$this  onStop ~~~~~~~~~~~~~~~~~~")
  }

  override fun onRestart() {
    super.onRestart()
    Logger.d(TAG, "$this onRestart ~~~~~~~~~~~~~~~~~~")
  }

  override fun onStart() {
    super.onStart()
    Logger.d(TAG, "$this onStart ~~~~~~~~~~~~~~~~~~")
  }

  override fun applyOverrideConfiguration(overrideConfiguration: Configuration?) {
    // 兼容androidX在部分手机切换语言失败问题
    if (overrideConfiguration != null) {
      val uiMode = overrideConfiguration.uiMode
      overrideConfiguration.setTo(baseContext.resources.configuration)
      overrideConfiguration.uiMode = uiMode
    }
    super.applyOverrideConfiguration(overrideConfiguration)
  }

  fun showProgressDialog(cancelable: Boolean) {

  }

  companion object {
    private const val TAG = "BaseActivity"
  }
}